﻿@model SearchBoxFrontModel
@using Microsoft.Ajax.Utilities
@using Nop.Web.Models.Catalog;
<div class="search-box-form @if (Model.AvailableRegions.Count > 1){<text>region-available</text>}">
    @{
        var hasCategory = false;
        var categoryText = "";
        if (Model.Cid > 0 && Model.AvailableCategories.FirstOrDefault(ac => ac.Value == Model.Cid.ToString()) != null)
        {
            hasCategory = true;
            categoryText = Model.AvailableCategories.FirstOrDefault(ac => ac.Value == Model.Cid.ToString()).Text;
        }
        //if (Model.CurrentRegionId > 0 && Model.AvailableRegions.FirstOrDefault(ar => ar.Value == Model.CurrentRegionId.ToString()) != null)
        //{
        //    regionText = Model.AvailableRegions.FirstOrDefault(ar => ar.Value == Model.CurrentRegionId.ToString()).Text;
        //}
    }
    @if (Model.AvailableRegions.Count > 1)
    {
        <div class="regions-select button-white-grad">
            <div class="dropdown">
                <div class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" id="region-dropdown">
                    <span class="region-name">@Model.UserDefaultRegions</span>
                </div>
                <ul class="dropdown-menu" aria-labelledby="region-dropdown">
                    @foreach (var reg in Model.AvailableRegions.Take(1))
                    {
                        <li data-text="@reg.Text" data-value="@reg.Value" class="@if(Model.Cid > 0){ if (reg.Value == Model.CurrentRegionId.ToString()){<text>selected</text>}} else if (reg.Value == "0"){<text>selected</text>}"><a href="#">@reg.Text</a></li>
                    }
                </ul>
            </div>
        </div>
    }
    @using (Html.BeginRouteForm("ProductSearch", FormMethod.Get, new { id = "header-search-bar-form" }))
    {
        <div class="search-button button-white-grad"><div class="search-box-button"><i class="fa fa-search"></i></div></div>
        if (Model.AvailableCategories.Count > 0)
        {
            <div class="search-category button-white-grad dropdown">
                <div class="dropdown-toggle category-dropdown @if(hasCategory){<text>has-category</text>}" id="search-box-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    <span class="search-box-category-empty"><i class="fa fa-bars"></i></span>
                    <span class="search-box-category-text">
                        @if (hasCategory)
                        { @categoryText }
                    </span>
                </div>
                <ul class="dropdown-menu dropdown-menu-right" aria-labelledby="search-box-dropdown">
                    @foreach (var sli in Model.AvailableCategories)
                    {
                        <li data-text="@sli.Text" data-value="@sli.Value" class="@if(Model.Cid > 0){ if (sli.Value == Model.Cid.ToString()){<text>selected</text>}} else if (sli.Value == "0"){<text>selected</text>}"><a href="/search?Cid=@sli.Value"><i class="fa fa-check"></i> @sli.Text</a></li>
                    }
                </ul>
            </div>
        }
        <div class="search-text @if (Model.AvailableCategories.Count > 0){<text>has-category</text>}">
            <input type="text" class="search-box form-control" id="search-box" @(Model.AutoCompleteEnabled ? Html.Raw(" autocomplete=\"off\"") : null) name="q" placeholder="@T("Search.Placeholder")" data-url="@(Url.RouteUrl("ProductSearchAutoComplete"))" data-minlength="@Model.SearchTermMinimumLength.ToString()" />
        </div>
        <script type="text/javascript">
            var search_terms = $("#search-box");
            var search_empty = '@T("Search.EnterSearchTerms")';
            var search_placeholder = '@T("Search.Placeholder")';
            $.support.placeholder = false;
            var test = document.createElement('input');
            if ('placeholder' in test) jQuery.support.placeholder = true;

            function check_small_search_form() {

                if ((search_terms.val() == "" && $("#Cid").val() == 0 && (!$("#Store_Id").length || $("#Store_Id").val() <= 1)) || search_terms.val() == search_empty || search_terms.val() == search_placeholder) {
                    search_terms.removeClass("empty placeholder");
                    search_terms.val(search_empty).addClass('empty').blur();
                    return false;
                }
                //alert(search_terms.val() + ',' + $("#Cid").val() + ',' + $("Store_Id").val());
                return true;
            }

            search_terms.focus(function () {
                if (search_terms.val() == search_empty || search_terms.val() == search_placeholder) {
                    search_terms.val('');
                }
                search_terms.removeClass("empty placeholder");
            }).blur(function () {
                if (!$.support.placeholder && search_terms.val() == "") {
                    search_terms.val(search_placeholder).addClass('placeholder').blur();
                }
            });

            $(document).ready(function () {
                if (!$.support.placeholder) {
                    search_terms.val(search_placeholder).addClass('placeholder').blur();
                }
            });
            $(".search-box-form .search-category li").click(function () {
                if ($(this).attr("data-value") != null) {
                    $(".search-box-form .search-category li").removeClass("selected");
                    $(this).addClass("selected");
                    $("input[name=@Html.NameFor(model => model.Cid)]").remove();
                    if (parseInt($(this).attr("data-value")) > 0) {
                        $(".search-box-form form").append("<input type='hidden' name='@Html.NameFor(model => model.Cid)' value='" + $(this).attr("data-value") + "' />");
                        $(".search-box-category-text").text($(this).attr("data-text"));
                        $(".search-box-form .search-category .category-dropdown").addClass("has-category");
                    } else {
                        $(".search-box-category-text").text("");
                        $(".search-box-form .search-category .category-dropdown").removeClass("has-category");
                    }
                }
            });

            $(".search-box-button").click(function () {
                $(this).closest("form").submit();
                //if (check_small_search_form()) {
                //    $(this).closest("form").submit();
                //}
            });

            $(".regions-select .dropdown-menu li").click(function () {
                $(".regions-select .region-name").text($(this).text());
            });

            @if (Model.AutoCompleteEnabled)
            {
                <text>
            $(function () {

                function getURLParameter(name) {
                    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
                }

                var querystring = getURLParameter("Q");
                if (querystring == null) {
                    querystring = getURLParameter("q");
                }
                if (querystring != null) {
                    $('#search-box').val(querystring);
                }

                $('#search-box').autocomplete({
                    delay: 500,
                    minLength: "@Model.SearchTermMinimumLength.ToString()",
                    source: '@(Url.RouteUrl("ProductSearchAutoComplete"))',
                    select: function (event, ui) {
                        $("#search-box").val(ui.item.label);
                        setLocation(ui.item.producturl);
                        return false;
                    },
                    response: function (event, ui) {
                        $(".search-box-loading").hide();
                    },
                    search: function (event, ui) {
                        $(".search-box-loading").show();
                    }
                }).data("ui-autocomplete")._renderItem = function (ul, item) {
                    ul.addClass('searchbox-autocomplete');
                    var t = item.label;
                    //html encode
                    t = htmlEncode(t);
                    return $("<li></li>")
                    .data("ui-autocomplete-item", item)
                    .append("<a>@(Model.ShowProductImagesInSearchAutoComplete ? Html.Raw("<img src='\" + item.productpictureurl + \"'>") : null )" + t + "</a>")
                    .appendTo(ul);
                };
            });
            </text>
            }
        </script>
        @Html.Widget("searchbox")
    }
</div>